package Web;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * @author wuhan
 * @date 2019/10/17 11:09
 */


class Send implements Runnable{
    private DatagramSocket datagramSocket;

    Send(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while (true){
            try {
                if (null == (line = bufferedReader.readLine())) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if ("886".equals(line))
                break;
            assert line != null;
            byte[] buf = line.getBytes();
            try {
                DatagramPacket datagramPacket = new DatagramPacket(buf,buf.length, InetAddress.getByName("172.20.10.11"),10101);
                datagramSocket.send(datagramPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

class Receiver implements Runnable{

    private DatagramSocket datagramSocket;

    Receiver(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                datagramSocket.receive(dp);
                String hostAddress = dp.getAddress().getHostAddress();
                String data = new String(dp.getData(), 0, dp.getLength());
                System.out.println(hostAddress + ":" + data);
            }
        }
        catch (Exception e){
            throw new RuntimeException("接受失败");
        }

    }
}


public class ChatAppMultiThread {
    public static void main(String[] args) throws SocketException {
        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket receSocket = new DatagramSocket(10101);
        Send send = new Send(sendSocket);
        Receiver receiver = new Receiver(receSocket);
        new Thread(send).start();
        new Thread(receiver).start();
    }
}
